//
//  MBRecruitController.m
//  LiveBroadcast
//
//  Created by 肖剑 on 2019/4/6.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBRecruitController.h"
#import "MITextView.h"
@interface MBRecruitController ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (weak, nonatomic) IBOutlet UITextField *nameL;
@property (weak, nonatomic) IBOutlet UITextField *phoneL;
@property (weak, nonatomic) IBOutlet UIButton *imageBtn;
@property (weak, nonatomic) IBOutlet MITextView *descriptionTV;
@property (nonatomic,strong)UIImage *selectImage;
@property (nonatomic,copy)NSString *imageUrl;


@end

@implementation MBRecruitController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"我要招人";
}
- (IBAction)selecImgClick:(UIButton *)sender {
    MB_WeakSelf(self);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photographAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself takePhoto];
    }];
    UIAlertAction *selectPictureAction = [UIAlertAction actionWithTitle:@"从图库中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself pushTZImagePickerController];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:photographAction];
    [alert addAction:selectPictureAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}


/*拍照*/
-(void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            NSMutableArray *mediaTypes = [NSMutableArray array];
            [mediaTypes addObject:(NSString *)kUTTypeImage];
            if (mediaTypes.count) {
                _imagePickerVc.mediaTypes = mediaTypes;
            }
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}

-(void)pushTZImagePickerController{
    MB_WeakSelf(self);
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.isSelectOriginalPhoto = YES;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowCrop = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        UIImage *image = photos.firstObject;
        UIImage *resultImage = [UIImage compressImage:image toKBByte:300];
        weakself.selectImage = resultImage;
        [weakself.imageBtn setImage:resultImage forState:UIControlStateNormal];
        [self getQiniuUpToken:resultImage];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *resultImage = [UIImage compressImage:image toKBByte:300];
    self.selectImage = resultImage;
    [self.imageBtn setImage:resultImage forState:UIControlStateNormal];
    [self getQiniuUpToken:resultImage];
}

#pragma mark - getter and setter
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}

/**
 获取七牛Token
 */
-(void)getQiniuUpToken:(UIImage *)img{
    NSDictionary *param = @{
                            };
    [MBHttpRequset requestWithUrl:kThird_Qiniu_Token setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        NSLog(@"kThird_Qiniu_Token = %@",AJson);
        QNUploadManager *manager = [[QNUploadManager alloc]init];
        NSData *data = UIImageJPEGRepresentation(img, 0.7);
        NSString *timeKey = [NSString stringWithFormat:@"%zd",[[MBTimeManager shateInstance]getCurrentTimestamp]];
        NSString *imageName = [NSString stringWithFormat:@"%@%@%@%@%@",@"upload/image/userId=",[MBUserModel sharedMBUserModel].userInfo.userId,@"-",timeKey,@".jpg"];
        
        [manager putData:data key:imageName token:AJson[@"upToken"] complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info.statusCode == 200) {
                
                self.imageUrl = [NSString stringWithFormat:@"%@",resp[@"key"]];
            }
        } option:nil];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}



- (IBAction)commitClick {
    if (self.nameL.text.length < 2 || self.phoneL.text.length != 11 || self.descriptionTV.text.length < 2) {
        [MBProgressHUD showError:@"请输入正确的个人信息"];
        return ;
    }
    if (self.imageUrl == nil) {
        [MBProgressHUD showError:@"请选择图片"];
        return ;
    }
    NSDictionary *dict = @{
                           @"name":self.nameL.text,
                           @"phone":self.phoneL.text,
                           @"userId":[NSString stringWithFormat:@"%@",[MBUserModel sharedMBUserModel].userInfo.userId],
                           @"recruitRequest":self.descriptionTV.text,
                           @"imageUrl":self.imageUrl
                           };
    [MBHttpRequset requestWithUrl:kTradeid_recruit_application setParams:dict isShowProgressView:YES success:^(id  _Nonnull AJson) {
        NSLog(@"kTradeid_recruit_participateData = %@",AJson);
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
